package com.movecar.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.model.ContactBean;
import com.movecar.model.FriendsBean;
import com.movecar.model.GroupBean;
import com.movecar.model.GroupMemberBean;
import com.movecar.sortlistview.CharacterParser;
import com.movecar.sortlistview.InvitationFriendsMemberAdapter;
import com.movecar.sortlistview.PinyinComparator;
import com.movecar.sortlistview.SideBar;
import com.movecar.sortlistview.SideBar.OnTouchingLetterChangedListener;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;

public class ActivityInvitationFriends extends Activity implements SectionIndexer, OnClickListener {
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private InvitationFriendsMemberAdapter adapter;
	//private ClearEditText mClearEditText;
	private FriendsBean mFriendsBean;
	private List<ContactBean> mContactBeanList;
	private CustomProgressDialog progressDialog = null;
	private List<GroupMemberBean> DateList;
	private RelativeLayout titleLayout;
	private TextView title;
	private TextView tvNofriends;
	/**
	 * 上次第一个可见元素，用于滚动时记录标识。
	 */
	private int lastFirstVisibleItem = -1;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<GroupMemberBean> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_friends);
		initViews();
	}

	private void initViews() {
		TextView main_title = (TextView) findViewById(R.id.title);
		main_title.setText("通讯录");
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		// titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
		// title = (TextView) this.findViewById(R.id.title_layout_catalog);
		tvNofriends = (TextView) this.findViewById(R.id.title_layout_no_friends);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (s.contains("@")) {
					sortListView.setSelection(0);
				} else if (position != -1) {
					sortListView.setSelection(position);
				}

			}
		});

		sortListView = (ListView) findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				Uri smsToUri = Uri.parse("smsto://" + SourceDateList.get(position).getPhone());
				Intent mIntent = new Intent(android.content.Intent.ACTION_SENDTO, smsToUri);
				mIntent.putExtra("sms_body", "给你推荐一个有趣的app 下载地址  :"
						+ "http://fuyunlehe.com/app");
				startActivityForResult(mIntent, 0);
			}
		});
		startProgressDialog();
		getContactList();
//		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
//		mClearEditText.setVisibility(View.GONE);
//		// 根据输入框输入值的改变来过滤搜索
//		mClearEditText.addTextChangedListener(new TextWatcher() {
//
//			@Override
//			public void onTextChanged(CharSequence s, int start, int before, int count) {
//				// 这个时候不需要挤压效果 就把他隐藏掉
//				titleLayout.setVisibility(View.GONE);
//				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
//				filterData(s.toString());
//			}
//
//			@Override
//			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//			}
//
//			@Override
//			public void afterTextChanged(Editable s) {
//			}
//		});
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<GroupMemberBean> filledData(List<GroupMemberBean> data) {
		List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>();

		for (int i = 0; i < data.size(); i++) {
			GroupMemberBean sortModel = new GroupMemberBean();
			sortModel.setName(data.get(i).getName());
			sortModel.setPhone(data.get(i).getPhone());
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(data.get(i).getName());
			String sortString = pinyin.substring(0, 1).toUpperCase();
			if (sortModel.getName().indexOf("好友申请") > 0) {
				sortModel.setSortLetters("好友申请");
			} else
			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}

			mSortList.add(sortModel);
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<GroupMemberBean> filterDateList = new ArrayList<GroupMemberBean>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
			tvNofriends.setVisibility(View.GONE);
		} else {
			filterDateList.clear();
			for (GroupMemberBean sortModel : SourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
		if (filterDateList.size() == 0) {
			tvNofriends.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public Object[] getSections() {
		return null;
	}

	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		return SourceDateList.get(position).getSortLetters().charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < SourceDateList.size(); i++) {
			String sortStr = SourceDateList.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 账号管理
		case R.id.btn_left:
			finish();
			break;
		case R.id.btn_right_long:
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("unchecked")
	private void getContactList() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryContactListNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				Type type = new TypeToken<List<ContactBean>>() {
				}.getType();
				Gson gson = new Gson();
				String result = (String) object;
				Object fromJson = gson.fromJson(result, type);

				try {
					mContactBeanList = (List<ContactBean>) fromJson;
				} catch (Exception e) {
					return;
				}

				DateList = new ArrayList<GroupMemberBean>();

				for (int i = 0; i < mContactBeanList.size(); i++) {
					GroupMemberBean bean = null;
					if (i < mContactBeanList.size()) {
						bean = new GroupMemberBean();
						bean.setName((mContactBeanList.get(i).getName()));
						bean.setPhone(mContactBeanList.get(i).getPhone());
					}
					DateList.add(bean);

				}

				SourceDateList = filledData(DateList);
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapter = new InvitationFriendsMemberAdapter(ActivityInvitationFriends.this, SourceDateList);
				sortListView.setAdapter(adapter);
				// sortListView.setOnScrollListener(new OnScrollListener() {
				// @Override
				// public void onScrollStateChanged(AbsListView view, int
				// scrollState) {
				// }
				//
				// @Override
				// public void onScroll(AbsListView view, int firstVisibleItem,
				// int visibleItemCount,
				// int totalItemCount) {
				// int section = getSectionForPosition(firstVisibleItem);
				// int nextSection = getSectionForPosition(firstVisibleItem +
				// 1);
				// int nextSecPosition = getPositionForSection(+nextSection);
				// if (firstVisibleItem != lastFirstVisibleItem) {
				// MarginLayoutParams params = (MarginLayoutParams)
				// titleLayout.getLayoutParams();
				// params.topMargin = 0;
				// titleLayout.setLayoutParams(params);
				// title.setText(SourceDateList.get(getPositionForSection(section)).getSortLetters());
				// }
				// if (nextSecPosition == firstVisibleItem + 1) {
				// View childView = view.getChildAt(0);
				// if (childView != null) {
				// int titleHeight = titleLayout.getHeight();
				// int bottom = childView.getBottom();
				// MarginLayoutParams params = (MarginLayoutParams)
				// titleLayout.getLayoutParams();
				// if (bottom < titleHeight) {
				// float pushedDistance = bottom - titleHeight;
				// params.topMargin = (int) pushedDistance;
				// titleLayout.setLayoutParams(params);
				// } else {
				// if (params.topMargin != 0) {
				// params.topMargin = 0;
				// titleLayout.setLayoutParams(params);
				// }
				// }
				// }
				// }
				// lastFirstVisibleItem = firstVisibleItem;
				// }
				// });
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(ActivityInvitationFriends.this,"与服务器连接失败，请检查网络");
			}
		}, GroupBean.class, AppConfig.USER).execute(params);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 0) {
			Alert.info(this, "发送成功");

		}

	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
